package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

//账号密码登录
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {

    @Resource
    XcUserMapper xcUserMapper;
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    CheckCodeClient checkCodeClient;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
//        账号
        String username = authParamsDto.getUsername();

//        todo 先取消验证码服务
//        验证码是否正确,需要远程调用验证码服务接口
//        String checkcode = authParamsDto.getCheckcode();//验证码
//        String checkcodekey = authParamsDto.getCheckcodekey();//验证码在redis中对应的key
//        if (StringUtils.isEmpty(checkcode) || StringUtils.isEmpty(checkcodekey)){
//            throw new RuntimeException("请输入验证码");
//        }
//// 远程调用验证码服务接口
//        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
//        if (verify == null || !verify){
//            throw new RuntimeException("验证码输入错误");
//        }

//        账号是否存在,根据账号查询数据库
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
//      查询到用户不存在,要返回null,spring security会报出异常用户不存在
        if (xcUser == null){
            return null;
        }
        String passwordDb = xcUser.getPassword();//加密密码
        String passwordForm = authParamsDto.getPassword();//原密码,用户输入的明文
        boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
        if (!matches){
            throw new RuntimeException("账号或密码错误");
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser,xcUserExt);
        return xcUserExt;
    }
}
